package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.Neusoft.service.NeusoftEmployeeChangeService;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.ContractConst;
import com.zhangtai.modules.constVo.EmployeeChangeConst;
import com.zhangtai.modules.constVo.SystemConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.TransferInfoDao;
import com.zhangtai.modules.entity.employee.EmployeeBpmEntity;
import com.zhangtai.modules.entity.employee.EmployeeChangeEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.transfer.TransferInfoEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.employee.EmployeeBpmService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.transfer.TransferInfoService;
import com.zhangtai.modules.vo.ContractNewVo;
import com.zhangtai.modules.vo.TransferInfoListVo;
import com.zhangtai.modules.vo.TransferInfoUpdateVo;
import com.zhangtai.modules.vo.TransferInfoVo;
import com.zhangtai.utils.*;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/transfer")
@Api(tags = "员工调动接口")
public class TransferController {

    @Autowired
    private LoginController loginController;
    @Autowired
    private TransferInfoService transferInfoService;

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;

    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private JobController jobController;
    @Autowired
    private CommonController commonController;
    @Autowired
    private TransferInfoDao transferInfoDao;
    @Autowired
    private EmployeeChangeController employeeChangeController;
    @Autowired
    private ContractController contractController;
    @Autowired
    private NeusoftEmployeeChangeService neusoftEmployeeChangeService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private EmployeeBpmService employeeBpmService;

    @GetMapping("/findEmpByCode")
    @ApiOperation(value = "根据工号查找员工信息")
    public R<TransferInfoEntity> findEmpByCode(@RequestParam String userCode, HttpServletRequest request) throws Exception {


        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", userCode).eq("is_delete", 0));
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            employeeInfoEntity = baseMssqlService.finEmpFromMssqlByCode(userCode);

            if (ObjectUtils.isEmpty(employeeInfoEntity)) {
                return R.ok();
            }
        }
        TransferInfoEntity infoEntity = new TransferInfoEntity();
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(userInfo)) {
            return R.error(SystemConst.loginInfoErro, "请先登录再查询！");
        }
        String name = userInfo.getString("name");

//        String name = "test";
        String code = userInfo.getString("usercode");

//        String code = "test";
        infoEntity.setApplyUserName(name); //管理员姓名
        infoEntity.setApplyCode(code); //管理员工号
        infoEntity.setUserCode(userCode);
        Integer jobLevelType = employeeInfoEntity.getJobLevelType();
        Long jobLevelId = employeeInfoEntity.getJobLevelId();
        String empName = employeeInfoEntity.getName(); //员工姓名
        Long oid = employeeInfoEntity.getOid();
        infoEntity.setOid(oid); //员工id

        infoEntity.setName(empName); //封装员工姓名
        infoEntity.setBeforeJobLevelType(jobLevelType);
        infoEntity.setBeforeJobLevelId(jobLevelId);
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
        infoEntity.setBeforeJobLevel(jobLevelNameById); //调动前职级


        Long beforeOrgId = employeeInfoEntity.getOrgId();
        String beforeOrg = jobController.getOrgNameById(beforeOrgId);

        infoEntity.setBeforeOrg(beforeOrg); //调动前公司
        infoEntity.setBeforeOrgId(beforeOrgId);

        Long beforeUnitId = employeeInfoEntity.getUnitId();

        String beforeUnit = jobController.getOrgNameById(beforeUnitId);

        infoEntity.setBeforeDepartment(beforeUnit);//调动前部门
        infoEntity.setBeforeDepartmentId(beforeUnitId);

        Long beforeJobId = employeeInfoEntity.getJobId();

        String beforeJob = jobController.getJobName(beforeJobId);

        infoEntity.setBeforeJob(beforeJob);//调动前岗位
        infoEntity.setBeforeJobId(beforeJobId);


        return R.ok(infoEntity);


    }

//    /**
//     * 先保存业务表，等审核通过后在修改主表
//     *
//     * @param transferInfoVo
//     * @return
//     */
//    @PostMapping("/saveOuterTransfer")
//    @ApiOperation(value = "跨单位调动保存")
//    @SysAuthorityLog(value = "跨单位调动保存")
//    @Transactional
//    @PreAuthorize("hasAuthority('emp:bmdd:update')")
//    public R saveOuterTransfer(@RequestBody @Valid TransferInfoVo transferInfoVo, HttpServletRequest request) throws Exception {
//        TransferInfoEntity transferInfoEntity = BeanUtilsMabach.doToDto(transferInfoVo, TransferInfoEntity.class);
//        //是否同一公司校验
//
//        transferInfoEntity.setCreateTime(new Date());
//
//        Long oid = transferInfoVo.getOid();
//        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
////        如果本地没有该员工，则先插入到本地
//        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
//            baseMssqlService.finEmpFromMssqlByCode(transferInfoVo.getUserCode());
//        }
//        String url = commonController.getFileUrls(transferInfoVo.getUrl(), transferInfoEntity.getOid(), "调动附件");
//        transferInfoEntity.setFileUrl(url);
//        transferInfoEntity.setTransferId(snowflakeIdWorker.nextId());
//        R r = transferInfoService.saveE(transferInfoEntity);
//        //        如果是内部调动，则直接生效不用走bpm
//
//        return r;

//    }

    @PostMapping("/updateOuterTransfer")
    @ApiOperation(value = "跨单位调动修改")
    @SysAuthorityLog(value = "跨单位调动修改")
    @Transactional
    @PreAuthorize("hasAuthority('emp:bmdd:update')")
    public R updateOuterTransfer(@RequestBody @Valid TransferInfoUpdateVo transferInfoUpdateVo)  {
        Boolean flag = false;
        TransferInfoEntity transferInfoEntity = BeanUtilsMabach.doToDto(transferInfoUpdateVo, TransferInfoEntity.class);
        Long oid = transferInfoEntity.getOid();
        if (CollectionUtils.isEmpty(transferInfoUpdateVo.getUrl())) {
            transferInfoEntity.setFileUrl("");
        } else {
            String url = commonController.getFileUrls(transferInfoUpdateVo.getUrl(), transferInfoEntity.getOid(), "调动附件");
            transferInfoEntity.setFileUrl(url);
        }
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(3);
        EmployeeInfoEntity infoEntity = employeeInfoService.getEmployeeInfoByRegularBpmStatus(status,oid);
        //查出带转正的员工数据，如果这个待转正信息（员工主表里面取）不为空且岗位id不相同，更新岗位信息到转正表
        if(!ObjectUtils.isEmpty(infoEntity)){
            EmployeeBpmEntity employeeBpmEntity = new EmployeeBpmEntity();
            employeeBpmEntity.setOid(oid);
            employeeBpmEntity.setJobId(transferInfoEntity.getAfterJobId());
            employeeBpmService.updateByIdE(employeeBpmEntity);
        }
        transferInfoService.updateByIdE(transferInfoEntity);
        flag = true;
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 先保存业务表，等审核通过后在修改主表
     *
     * @param transferInfoVo
     * @return
     */
    @PostMapping("/saveTransfer")
    @ApiOperation(value = "保存员工调动信息")
    @SysAuthorityLog(value = "保存员调动信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:bmdd:update')")
    public R saveTransfer(@RequestBody @Valid TransferInfoVo transferInfoVo) {
        TransferInfoEntity transferInfoEntity = BeanUtilsMabach.doToDto(transferInfoVo, TransferInfoEntity.class);
        transferInfoEntity.setCreateTime(new Date());

        Long oid = transferInfoVo.getOid();
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
//        如果本地没有该员工，则先插入到本地
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            baseMssqlService.finEmpFromMssqlByCode(transferInfoVo.getUserCode());
        }
        String url = commonController.getFileUrls(transferInfoVo.getUrl(), transferInfoEntity.getOid(), "调动附件");
        transferInfoEntity.setFileUrl(url);
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(3);
        EmployeeInfoEntity infoEntity = employeeInfoService.getEmployeeInfoByRegularBpmStatus(status,oid);
        //查出带转正的员工数据，如果这个待转正信息（员工主表里面取）不为空且岗位id不相同，更新岗位信息到转正表
        if(!ObjectUtils.isEmpty(infoEntity)){
            EmployeeBpmEntity employeeBpmEntity = new EmployeeBpmEntity();
            employeeBpmEntity.setOid(oid);
            employeeBpmEntity.setJobId(transferInfoEntity.getAfterJobId());
            employeeBpmService.updateByIdE(employeeBpmEntity);
        }
        transferInfoEntity.setTransferId(snowflakeIdWorker.nextId());
        R r = transferInfoService.saveE(transferInfoEntity);
//        //        如果是内部调动，则直接生效不用走bpm
//        if (transferInfoVo.getType() != null && transferInfoVo.getType().equals(0)) {
//            transferToEmployee(transferInfoEntity,null,null);
//        }
        return r;

    }

    @PostMapping("/updateTransfer")
    @ApiOperation(value = "修改员工内部调动信息")
    @SysAuthorityLog(value = "修改员工内部调动信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:bmdd:update')")
    public R updateTransfer(@RequestBody @Valid TransferInfoUpdateVo transferInfoUpdateVo) {
        TransferInfoEntity transferInfoEntity = BeanUtilsMabach.doToDto(transferInfoUpdateVo, TransferInfoEntity.class);
        Long oid = transferInfoEntity.getOid();
        if (CollectionUtils.isEmpty(transferInfoUpdateVo.getUrl())) {
            transferInfoEntity.setFileUrl("");
        } else {
            String url = commonController.getFileUrls(transferInfoUpdateVo.getUrl(), oid, "调动附件");
            transferInfoEntity.setFileUrl(url);
        }
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(3);
        EmployeeInfoEntity infoEntity = employeeInfoService.getEmployeeInfoByRegularBpmStatus(status,oid);
        //查出带转正的员工数据，如果这个待转正信息（员工主表里面取）不为空且岗位id不相同，更新岗位信息到转正表
        if(!ObjectUtils.isEmpty(infoEntity)){
            EmployeeBpmEntity employeeBpmEntity = new EmployeeBpmEntity();
            employeeBpmEntity.setOid(oid);
            employeeBpmEntity.setJobId(transferInfoEntity.getAfterJobId());
            employeeBpmService.updateByIdE(employeeBpmEntity);
        }
        transferInfoService.updateByIdE(transferInfoEntity);
        return R.ok();
    }

    /**
     * 调动信息修改雇佣表信息
     *
     * @param infoEntity
     */
    @Transactional
    public void transferToEmployee(TransferInfoEntity infoEntity, BigDecimal base,BigDecimal module) {
//        如果是部门内部调动 ，不用走审批，直接修改
        EmployeeInfoEntity employeeInfoEntity = new EmployeeInfoEntity();
        employeeInfoEntity.setOid(infoEntity.getOid());
        employeeInfoEntity.setCode(infoEntity.getUserCode());
        employeeInfoEntity.setName(infoEntity.getName());
        employeeInfoEntity.setOrgId(infoEntity.getAfterOrgId());
        employeeInfoEntity.setUnitId(infoEntity.getAfterDepartmentId());
        employeeInfoEntity.setJobId(infoEntity.getAfterJobId());
        employeeInfoEntity.setJobLevelId(infoEntity.getAfterJobLevelId());
        employeeInfoEntity.setJobLevelType(infoEntity.getAfterJobLevelType());
//        employeeInfoEntity.setIsReinstate(2);//旧员工 员工调动
        employeeInfoService.updateByIdE(employeeInfoEntity);
        EmployeeInfoEntity info = employeeInfoService.getByIdE(infoEntity.getOid());
        //如果合同需要重新签署则生成解除合同数据
        afreshContract(infoEntity);
        //生成员工变更记录信息
        EmployeeChangeEntity changeEntity = new EmployeeChangeEntity();
        changeEntity.setJobName(jobController.jobMap.get(infoEntity.getAfterJobId()));
        changeEntity.setMobile(info.getMobile());
        changeEntity.setName(infoEntity.getName());
        changeEntity.setOid(infoEntity.getOid());
        changeEntity.setOrgName(jobController.orgMap.get(infoEntity.getAfterOrgId()));
        if (infoEntity.getTransferType().equals(0)) {
            changeEntity.setType(EmployeeChangeConst.CHANGE_TYPE_INNER_TRANSFER);
        } else if (infoEntity.getTransferType().equals(2)) {
            changeEntity.setType(EmployeeChangeConst.CHANGE_TYPE_ORG_TRANSFER);
        } else {
            changeEntity.setType(EmployeeChangeConst.CHANGE_TYPE_UNIT_TRANSFER);
        }
        changeEntity.setUnitId(infoEntity.getAfterDepartmentId());
        changeEntity.setUnitName(jobController.orgMap.get(infoEntity.getAfterDepartmentId()));
        changeEntity.setCreateTime(new Date());
        employeeChangeController.addEmployeeChangeInfo(changeEntity);
        //调用调动异动接口
        neusoftEmployeeChangeService.uploadTransferChange(infoEntity,base,module);
    }

    @PostMapping("/getTransferInfoList")
    @ApiOperation(value = "员工调动列表")
    @PreAuthorize("hasAuthority('emp:bmdd:get')")
    public R<PageResult<TransferInfoEntity>> getTransferInfoList(@RequestBody @Valid TransferInfoListVo transferInfoListVo, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> jobIds = null;
        List<Long> jobSystemIds = null;
        if (!StringUtil.isNullOrEmpty(transferInfoListVo.getJobSystem())) {
            jobSystemIds = baseMssqlService.findSystemIdByName(transferInfoListVo.getJobSystem());
        }
        if (!StringUtil.isNullOrEmpty(transferInfoListVo.getJob())) {
            jobIds = baseMssqlService.findJobIdByJobName(transferInfoListVo.getJob());
        }
        PageResult<TransferInfoEntity> page = transferInfoService.queryPage(transferInfoListVo.getTransferType(),transferInfoListVo.getDepartment(), transferInfoListVo.getOrg(), transferInfoListVo.getUserCode(),
                transferInfoListVo.getName(), transferInfoListVo.getType(), transferInfoListVo.getDealStatus(), jobIds, jobSystemIds, orgIds, transferInfoListVo.getPageNum(), transferInfoListVo.getPageSize());
        List<TransferInfoEntity> transferInfoEntities = page.getList();
        for (TransferInfoEntity entity : transferInfoEntities) {
            //            根据id去换缓存中获取组织名称
            String beforeOrgName = jobController.getOrgNameById(entity.getBeforeOrgId());
            String beforeUnitName = jobController.getOrgNameById(entity.getBeforeDepartmentId());
            //根据id去换缓存中获取岗位名称
            String beforeJobName = jobController.getJobName(entity.getBeforeJobId());

            //根据id去换缓存中获取职级名称
            String beforeJobLevelName = jobController.getJobLevelNameById(entity.getBeforeJobLevelId());
            entity.setBeforeOrg(beforeOrgName);
            entity.setBeforeDepartment(beforeUnitName);
            entity.setBeforeJob(beforeJobName);
            entity.setBeforeJobLevel(beforeJobLevelName);
            String afterOrgName = jobController.getOrgNameById(entity.getAfterOrgId());
            entity.setAfterOrg(afterOrgName);
            String afterUnitName = jobController.getOrgNameById(Long.valueOf(entity.getAfterDepartmentId()));
            entity.setAfterDepartment(afterUnitName);
            //根据id去换缓存中获取岗位名称
            String afterJobName = jobController.getJobName(entity.getAfterJobId());
            entity.setAfterJob(afterJobName);

            //根据id去换缓存中获取职级名称
            String afterJobLevelName = jobController.getJobLevelNameById(entity.getAfterJobLevelId());
            entity.setAfterJobLevel(afterJobLevelName);
        }
        return R.ok(page);
    }

    @DeleteMapping("/deleteTransferInf")
    @ApiOperation(value = "根据id删除")
    @SysAuthorityLog(value = "根据id删除")
    @PreAuthorize("hasAuthority('emp:bmdd:update')")
    @Transactional
    public R delete(@RequestParam("transferId") Long transferId, HttpServletRequest request) throws Exception {
        TransferInfoEntity entity = transferInfoService.getByIdE(transferId);
        if (ObjectUtils.isEmpty(entity)) {
            return R.error("调动信息不存在，无法删除！");
        }
        R checkR = loginController.checkOrgPermission(request, entity.getBeforeDepartmentId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        R r = transferInfoService.removeOneById(transferId);
        return r;
    }

    @PostMapping("/updateHireStatus")
    @ApiOperation(value = "更新调动入职状态")
    @PreAuthorize("hasAuthority('emp:bmdd:update')")
    @Transactional
    public R updateHireStatus(String transferId,String hireDate) {
        TransferInfoEntity infoEntity = transferInfoService.getByIdE(Long.parseLong(transferId));
        Date date = DateUtils.parseDateYMDHMSS(hireDate);
        infoEntity.setIsHireDone(1);
        infoEntity.setDealStatus(1);
        infoEntity.setRealHireDate(date);
        infoEntity.setBeginTransferDate(date);
        List<TransferInfoEntity> oldList = transferInfoDao.selectList(new QueryWrapper<TransferInfoEntity>().eq("oid", infoEntity.getOid()).eq("is_hire_done", 1).orderByDesc("begin_transfer_date"));
        //将上次调动的结束时间设为 这次调动的开始时间
        if (!CollectionUtils.isEmpty(oldList)) {
            TransferInfoEntity old = oldList.get(0);
            old.setEndTransferDate(date);
            transferInfoDao.updateById(old);
        }
        EmployeeInfoEntity employeeInfoEntity= employeeInfoService.getByIdE(infoEntity.getOid());

        transferToEmployee(infoEntity,employeeInfoEntity.getMonthlySalary().subtract(employeeInfoEntity.getPerformance()),employeeInfoEntity.getMonthlySalary());
        transferInfoService.updateByIdE(infoEntity);
        return R.ok();
    }

    @PostMapping("/updateAuditStatus")
    @ApiOperation(value = "更新调动入职状态(内部调动)")
    @PreAuthorize("hasAuthority('emp:bmdd:update')")
    @Transactional
    public R updateAuditStatus(String id)  {
        TransferInfoEntity infoEntity = transferInfoService.getByIdE(Long.parseLong(id));
        Date hireDate = infoEntity.getBeginTransferDate();
        infoEntity.setRealHireDate(hireDate);
        infoEntity.setAuditStatus(2);
        infoEntity.setDealStatus(1);
        infoEntity.setIsHireDone(1);
        List<TransferInfoEntity> oldList = transferInfoDao.selectList(new QueryWrapper<TransferInfoEntity>().eq("oid", infoEntity.getOid()).eq("is_hire_done", 1).orderByDesc("begin_transfer_date"));
        //将上次调动的结束时间设为 这次调动的开始时间
        if (!CollectionUtils.isEmpty(oldList)) {
            TransferInfoEntity old = oldList.get(0);
            old.setEndTransferDate(hireDate);
            transferInfoDao.updateById(old);
        }
        transferToEmployee(infoEntity,null,null);
        transferInfoService.updateByIdE(infoEntity);
        return R.ok();
    }

    public void afreshContract(TransferInfoEntity transferInfoEntity){
        if(transferInfoEntity.getIsAfreshContract().equals(1)){
            ContractNewVo vo = new ContractNewVo();
            vo.setOid(transferInfoEntity.getOid());
            //晋升
            if(transferInfoEntity.getTransferType().equals(3)||transferInfoEntity.getTransferType().equals(4)){
                vo.setOperateType(ContractConst.CONTRACT_OPERATE_PROMOTION);
            }
            //降级
            else if(transferInfoEntity.getTransferType().equals(2)){
                vo.setOperateType(ContractConst.CONTRACT_OPERATE_DEMOTION);
            }else{
                vo.setOperateType(ContractConst.CONTRACT_OPERATE_TRANSFER);
            }
            vo.setType(ContractConst.CONTRACT_TYPE_TERMINATE);
            vo.setContractType(ContractConst.CONTRACT_MANAGER_TERMINATE);
            //结束当天
            vo.setContractBeginDate(DateUtils.addDateDays(transferInfoEntity.getBeginTransferDate(),-1));
            vo.setRelateId(transferInfoEntity.getTransferId());
            contractController.saveNewContract(vo);
        }
    }


}
